<template>
  <div class="employee-add">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>新增员工</h2>
      <el-button @click="goBack">返回列表</el-button>
    </div>

    <!-- 员工信息表单 -->
    <div class="form-container">
      <el-form
        ref="employeeFormRef"
        :model="employeeForm"
        :rules="employeeRules"
        label-width="120px"
        size="large"
      >
        <el-card header="基本信息" class="form-card">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="员工姓名" prop="name">
                <el-input
                  v-model="employeeForm.name"
                  placeholder="请输入员工姓名"
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="员工类型" prop="type">
                <el-select
                  v-model="employeeForm.type"
                  placeholder="请选择员工类型"
                  style="width: 100%"
                  @change="handleTypeChange"
                >
                  <el-option label="全职员工" value="FULL_TIME" />
                  <el-option label="兼职员工" value="PART_TIME" />
                  <el-option label="临时工" value="TEMPORARY" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="薪资等级" prop="salaryLevel">
                <el-input-number
                  v-model="employeeForm.salaryLevel"
                  :min="1"
                  :max="10"
                  placeholder="请输入薪资等级"
                  style="width: 100%"
                />
                <div class="form-tip">建议范围1-10，具体按公司规则</div>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="电话号码" prop="phone">
                <el-input
                  v-model="employeeForm.phone"
                  placeholder="请输入电话号码"
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="邮箱地址" prop="email">
                <el-input
                  v-model="employeeForm.email"
                  placeholder="请输入邮箱地址"
                  clearable
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="入职日期" prop="hireDate">
                <el-date-picker
                  v-model="employeeForm.hireDate"
                  type="date"
                  placeholder="请选择入职日期"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="员工状态" prop="status">
                <el-radio-group v-model="employeeForm.status">
                  <el-radio value="ACTIVE">在职</el-radio>
                  <el-radio value="INACTIVE">离职</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>

        <el-card header="工作配置" class="form-card">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="优先级" prop="priority">
                <el-input-number
                  v-model="employeeForm.priority"
                  :min="1"
                  :max="10"
                  placeholder="请输入优先级"
                  style="width: 100%"
                />
                <div class="form-tip">
                  优先级范围1-10，数字越大优先级越高
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="工作能力">
                <el-rate
                  v-model="employeeForm.workCapacity"
                  :max="5"
                  show-text
                  :texts="['很差', '较差', '一般', '良好', '优秀']"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="备注信息">
            <el-input
              v-model="employeeForm.remarks"
              type="textarea"
              :rows="3"
              placeholder="请输入备注信息（可选）"
              maxlength="200"
              show-word-limit
            />
          </el-form-item>
        </el-card>

        <!-- 操作按钮 -->
        <div class="form-actions">
          <el-button size="large" @click="goBack">取消</el-button>
          <el-button type="primary" size="large" @click="handleSubmit" :loading="submitting">
            保存
          </el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { createEmployee } from '@/api/employee'

const router = useRouter()
const employeeFormRef = ref()
const submitting = ref(false)

// 员工表单数据
const employeeForm = reactive({
  name: '',
  phone: '',
  email: '',
  type: '',
  salaryLevel: 1,
  priority: 5,
  hireDate: '',
  status: 'ACTIVE',
  workCapacity: 3,
  remarks: ''
})

// 表单验证规则
const employeeRules = {
  name: [
    { required: true, message: '请输入员工姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '姓名长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入电话号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择员工类型', trigger: 'change' }
  ],
  salaryLevel: [
    { required: true, message: '请输入薪资等级', trigger: 'blur' },
    { type: 'number', min: 1, max: 10, message: '薪资等级必须在1-10之间', trigger: 'blur' }
  ],
  priority: [
    { required: true, message: '请输入优先级', trigger: 'blur' },
    { type: 'number', min: 1, max: 10, message: '优先级必须在1-10之间', trigger: 'blur' }
  ],
  hireDate: [
    { required: true, message: '请选择入职日期', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择员工状态', trigger: 'change' }
  ]
}

// 员工类型变化处理
const handleTypeChange = (type) => {
  // 根据员工类型设置默认优先级
  const priorityMap = {
    FULL_TIME: 8,
    PART_TIME: 5,
    TEMPORARY: 3
  }
  employeeForm.priority = priorityMap[type] || 5
}

// 提交表单
const handleSubmit = async () => {
  try {
    await employeeFormRef.value.validate()
    submitting.value = true
    // 构造后端所需的字段与类型
    const mapTypeToInt = (t) => {
      switch (t) {
        case 'FULL_TIME':
          return 1
        case 'PART_TIME':
          return 2
        case 'TEMPORARY':
          return 3
        default:
          return null
      }
    }
    const mapStatusToInt = (s) => (s === 'ACTIVE' ? 1 : 0)
    const formatHireDate = (d) => (d ? `${d}T00:00:00` : null)

    const payload = {
      name: employeeForm.name,
      phone: employeeForm.phone,
      email: employeeForm.email,
      salaryLevel: employeeForm.salaryLevel,
      employeeType: mapTypeToInt(employeeForm.type),
      status: mapStatusToInt(employeeForm.status),
      hireDate: formatHireDate(employeeForm.hireDate)
    }

    await createEmployee(payload)
    ElMessage.success('员工创建成功')
    
    // 跳转回列表页面
    router.push('/employees')
  } catch (error) {
    if (error.message) {
      ElMessage.error('创建失败：' + error.message)
    }
  } finally {
    submitting.value = false
  }
}

// 返回列表页面
const goBack = () => {
  router.push('/employees')
}
</script>

<style scoped>
.employee-add {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
}

.form-container {
  max-width: 800px;
}

.form-card {
  margin-bottom: 20px;
}

.form-card :deep(.el-card__header) {
  background-color: #f5f7fa;
  font-weight: 600;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.form-actions {
  text-align: center;
  margin-top: 30px;
  padding: 20px;
  border-top: 1px solid #ebeef5;
}

.form-actions .el-button {
  margin: 0 10px;
  min-width: 100px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-card) {
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
</style>